﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace LbangCMS.Extensions
{
    public static class ModelStateExtensions
    {
        public static IEnumerable<string> AllModelStateErrors(this ModelStateDictionary modelState)
        {
            var result = new List<string>();
            var errorFieldsAndMsgs = modelState.Where(m => m.Value.Errors.Any())
                .Select(x => new { x.Key, x.Value.Errors });
            foreach (var item in errorFieldsAndMsgs)
            {
                var fieldKey = item.Key;
                var fieldErrors = item.Errors
                    .Select(e => e.ErrorMessage);
                result.AddRange(fieldErrors);
            }
            return result;
        }
        public static string ToHtmlMessage(this ModelStateDictionary modelState)
        {
            var messages = new List<string>();
            var errorFieldsAndMsgs = modelState.Where(m => m.Value.Errors.Any())
                .Select(x => new { x.Key, x.Value.Errors });
            foreach (var item in errorFieldsAndMsgs)
            {
                var fieldKey = item.Key;
                var fieldErrors = item.Errors
                    .Select(e => e.ErrorMessage);
                messages.AddRange(fieldErrors);
            }
            var html = "<ul class='state-error'>";
            foreach (var item in messages)
            {
                html += "<li>" + item + "</li>";
            }
            html += "</ul>";
            return html;
        }
    }
}